<?php
namespace app\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class Barn extends Model
{
    const IS_DELETE_NO = 0;
    const STATUS_NORMAL = 10;
    const STATUS_ABNORMAL = 20;

    /**
     * 判断数据是否存在
     *
     * @param integer $factoryId
     * @param int $outId
     * @return int
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function checkOutId(int $factoryId, int $outId)
    {
        $info = $this->field('id')
            ->where('factory_id', $factoryId)
            ->where('out_id', $outId)
            ->where('delete_time', self::IS_DELETE_NO)
            ->find();
        if (!$info) {
            return null;
        }

        return $info['id'];
    }

    /**
     * @Description 检查同一猪厂栋名是否存在
     * @author: zj
     * @param int $factoryId
     * @param string $name
     * @time 2023/09/20 10:07:47
     * @return mixed|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function checkName(int $factoryId,string $name)
    {
        $info = $this->field('id')
            ->where('factory_id', $factoryId)
            ->where('name', $name)
            ->where('delete_time', self::IS_DELETE_NO)
            ->find();
        if (!$info) {
            return null;
        }

        return $info['id'];
    }

    /**
     * @Description 关联栏
     * @author: zj
     * @time 2023/09/04 11:37:04
     * @return \think\model\relation\HasMany
     */
//    public function fence()
//    {
//        return $this->hasMany(Fence::class,"building_id","id");
//    }

    /**
     * @Description 猪厂栋的统计
     * @author: zj
     * @param int $factoryId
     * @time 2024/03/19 10:27:35
     * @return int
     * @throws DbException
     */
    public function checkBarnCount(int $factoryId)
    {
        return $this
            -> where('factory_id',$factoryId)
            -> where('delete_time',self::IS_DELETE_NO)
            -> count() ?? 0;
    }

    /**
     * @Description 获取猪厂全部栋列表
     * @param int $factoryId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @time 2023/09/04 16:08:08
     * @author: zj
     */
    public function getAllList(int $factoryId)
    {
        return $this->field('id,name')
            ->where('factory_id',$factoryId)
            ->where('delete_time',self::IS_DELETE_NO)
            ->select()
            ->toArray();
    }
}